FROM node:22-alpine AS base
#FROM node:22-bullseye-slim as base
RUN apk update && apk add --no-cache libc6-compat

RUN npm install pnpm turbo --global
RUN pnpm config set store-dir ~/.pnpm-store

FROM base AS pruner
WORKDIR /app
COPY . .
RUN turbo prune server --docker

FROM base AS builder
WORKDIR /app
ARG DATABASE_URL
ENV DATABASE_URL=$DATABASE_URL
RUN apk add --no-cache postgresql-client

COPY --from=pruner /app/out/json/ .
COPY --from=pruner /app/out/pnpm-lock.yaml ./pnpm-lock.yaml
COPY --from=pruner /app/out/pnpm-workspace.yaml ./pnpm-workspace.yaml
RUN --mount=type=cache,id=pnpm,target=~/.pnpm-store pnpm install
COPY --from=pruner /app/out/full/ .
COPY apps/server/migrate-and-start.sh ./apps/server/
COPY turbo.json turbo.json

RUN pnpm install
WORKDIR /app/apps/server
RUN npx prisma generate --schema src/prisma/schema.prisma
WORKDIR /app
RUN turbo build --filter server
RUN --mount=type=cache,id=pnpm,target=~/.pnpm-store pnpm prune --prod --no-optional
RUN rm -rf ./**/*/src


FROM base AS server
WORKDIR /app
RUN apk add --no-cache \
    chromium \
    nss \
    ca-certificates
RUN rm -rf /var/cache/apk/*
ENV PUPPETEER_EXECUTABLE_PATH=/usr/bin/chromium-browser
RUN addgroup --system --gid 1001 nodejs && adduser --system --uid 1001 nestjs
COPY --from=builder --chown=nestjs:nodejs /app/apps/server/dist ./server/dist
COPY --from=builder --chown=nestjs:nodejs /app/apps/server/package.json ./server/package.json
COPY --chown=nestjs:nodejs wait-for.sh ./wait-for.sh
RUN chmod +x wait-for.sh
WORKDIR /app/server
RUN pnpm install --only=production
RUN --mount=type=cache,id=pnpm,target=~/.pnpm-store pnpm prune --prod --no-optional
RUN rm -rf ./**/*/src
RUN rm -rf node_modules/rxjs/src/
WORKDIR /app
USER nestjs
EXPOSE 3000
ENV PORT=3000
ENV ENV_NODE=production
CMD ["node","server/dist/main.js"]
